package cn.cs.service.impl;

import cn.cs.client.AccountDetailClient;
import cn.cs.client.RestClientUserClient;
import cn.cs.client.RestInvoiceClient;
import cn.cs.common.Constants;
import cn.cs.common.EmptyUtils;
import cn.cs.common.Page;
import cn.cs.pojo.ClientUser;
import cn.cs.pojo.Invoice;
import cn.cs.service.InvoiceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class InvoiceServiceImpl implements InvoiceService {

    @Resource
    private RestInvoiceClient invoiceClient;

    @Resource
    private RestClientUserClient clientUserClient;

    @Resource
    private AccountDetailClient accountDetailClient;


    @Override
    public Invoice getInvoiceById(String id) throws Exception {
        return invoiceClient.getInvoiceById(id);
    }

    @Override
    public List<Invoice> getInvoiceListByUserId(String userId, String userPid) throws Exception {
        return invoiceClient.getInvoiceListByUserId(userId, userPid);
    }

    @Override
    public Integer getInvoiceCountByMap(Map<String, Object> param) throws Exception {
        return invoiceClient.getInvoiceCountByMap(param);
    }

    @Override
    public Integer addInvoice(Invoice invoice) throws Exception {
        invoice.setCreateDate(new Date());
        invoice.setModifyDate(new Date());
        return invoiceClient.addInvoice(invoice);
    }

    @Override
    public Integer modifyInvoice(Invoice invoice) throws Exception {
        invoice.setModifyDate(new Date());
        return invoiceClient.modifyInvoice(invoice);
    }

    @Override
    public Integer deleteInvoiceById(Long id) throws Exception {
        return invoiceClient.deleteInvoiceById(id);
    }

    @Override
    public Integer updateAccountDetailByIds(String ids) throws Exception {
        return accountDetailClient.updateAccountDetailByIds(ids.split(","));
    }

    @Override
    public Page<Invoice> queryInvoicePageByMap(Map<String, Object> param, Integer pageNo, Integer pageSize) throws Exception {
        Integer total = invoiceClient.getInvoiceCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Invoice> invoiceList = invoiceClient.getInvoiceListByMap(param);
        for(Invoice a:invoiceList){
            String userId = a.getUserId();
            ClientUser clientUser = clientUserClient.getClientUserById(userId);
            if(EmptyUtils.isNotEmpty(clientUser)){
                a.setUserPhone(clientUser.getPhone());
            }
        }
        page.setRows(invoiceList);
        return page;
    }

}
